<template>
<div :class="[$style.container]" @keyup.enter="onConfirm">
<el-dialog title="编辑分组" :visible.sync="visible" width="30%">
  <el-form size="small" label-position="top" :rules="rules" :model="form" @submit.native.prevent="" ref="fm">
    <el-form-item prop="name">
      <el-input v-model="form.name" placeholder="输入分组名称" clearable ref="nameInput"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer">
    <el-button size="small" @click="onCancel" class="px-5">取 消</el-button>
    <el-button size="small" type="primary" @click="onConfirm" :loading="submitting" :disabled="disabled" class="px-5">确 定</el-button>
  </span>
</el-dialog>
</div>
</template>

<script lang="ts">

import { createGroup, updateGroup } from '@/api/star'
import { Vue, Component, Prop, Emit, Ref } from 'vue-property-decorator'
import { textValidator } from '@/config/validator'

@Component
export default class StarGroupEditModal extends Vue {
  @Ref() fm!: any

  visible = false

  data: any = null

  resolve: ((value: any) => void) | null = null

  reject: (() => void) | null = null

  submitting = false

  form = {
    name: ''
  }

  rules = {
    name: [
      { required: true, message: '请输入文档名称' }
    ]
  }

  get disabled () {
    return this.data?.name === this.form.name
  }

  open (data?: any) {
    this.data = data || null
    this.visible = true
    this.$nextTick(() => {
      this.fm.resetFields()
      this.form.name = data?.name || ''
      const input = this.$refs.nameInput as any
      input.focus()
    })
    return new Promise((resolve, reject) => {
      this.resolve = resolve
      this.reject = reject
    })
  }

  onCancel () {
    this.visible = false
    if (this.reject) this.reject()
  }

  onConfirm () {
    this.fm.validate().then((valid: boolean) => {
      if (!valid) return
      this.submitting = true
      const request = this.data ? updateGroup(this.data?.id, this.form) : createGroup(this.form)
      request.then(() => {
        this.visible = false
        if (this.resolve) this.resolve(this.form)
      }).finally(() => {
        this.submitting = false
      })
    })
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {

}

</style>
